<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" v-if="!state.addModal" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button
            class="tableFontSize"
            type="primary"
            link
            size="small"
            @click="editBtn(row.row.row)"
            >编辑</el-button
          >
          <el-button
            class="tableFontSize"
            type="primary"
            link
            size="small"
            @click="deleteBtn(1,row.row.row)"
            >删除
          </el-button>
        </span>
      </template>
      <template v-slot:opraCurdBtnAll>
        <span
          :class="state.addModal ? 'listInfoBtn active' : 'listInfoBtn'"
          @click="addBtn"
        >
          <svg-icon
            :class="state.addModal ? 'active' : ''"
            class-name="search-icon"
            icon-class="xinzeng"
          />
          新增
        </span>
        <span :class="'listInfoBtn'" @click="deleteBtn(0)">
          <svg-icon class-name="search-icon" icon-class="shanchu" />
          删除
        </span>
      </template>
      <template v-slot:selectNamelist> 组合累积计时 </template>
    </list_controller>
    <div class="addBox" v-if="state.addModal">
      <stepcom :stepNum="stepNum" :stepList="stepList"></stepcom>
      <div class="step box_one" v-if="stepNum == 1">
        <div class="item">
          设置组合累积计时名称
          <el-input v-model="state.formData.name" style="width: 289px;margin:20px 0 0 0;" placeholder="请输入" />
        </div>
        <div class="btnSubmit">
          <el-button type="info" @click="nextStep(9)">取消</el-button>
          <el-button type="primary" @click="nextStep(1)">下一步</el-button>
        </div>
      </div>
      <div v-if="stepNum == 2" class="step">
          <p class="p_title">查询测点</p>
          <div style="background:rgba(91, 109, 128, .04);margin:0 10px;padding: 10px;">
              <querybox :queryList="state.querystwo" @query="queryClick"></querybox>
              <vxe-table height="200" :data="state.listAnalog" border="inner">
                  <vxe-column field="pointId" title="测点编号"></vxe-column>
                  <vxe-column field="sensorName" title="传感器名称"></vxe-column>
                  <vxe-column field="placeName" title="地点"></vxe-column>
                  <vxe-column title="操作" :min-width="80">
                      <template #default="{ row,rowIndex }">
                          <el-button type="text" @click="selectClick(row,rowIndex)">选择</el-button>
                      </template>
                  </vxe-column>
              </vxe-table>
          </div>
          <p class="p_title">已选因子({{ state.yinziList.length }})</p>
          <yincard :gaojiBtnShow="true" :cardList="state.yinziList" :biaodaList="state.biaodaList" :listAnalog="state.listAnalog"></yincard>
          <div class="btnSubmit">
              <el-button type="info" @click="nextStep(9)">取消</el-button>
              <el-button type="info" @click="nextStep(0)">上一步</el-button>
              <el-button type="primary" @click="nextStep(2)">下一步</el-button>
          </div>
      </div>
      <div v-if="stepNum == 3" class="step">
          <p class="p_title">已选因子({{state.yinziList.length}})</p>
          <div style="background:rgba(91, 109, 128, .04);margin:0 10px;padding: 10px;">
              <vxe-table height="200" :data="state.yinziList" border="inner">
                  <vxe-column type="seq" :width="55" title="序号"></vxe-column>
                  <vxe-column field="title" title="管道名称"></vxe-column>
                  <vxe-column field="place" title="地点"></vxe-column>
                  <vxe-column title="累积计时模式">
                      <template #default="{ row }">
                        <el-select v-model="row.accumulationTimeMode" placeholder="请选择" style="width: 240px">
                          <el-option
                            v-for="item in row.timeMod"
                            :key="item"
                            :label="item"
                            :value="item"
                          />
                        </el-select>
                      </template>
                  </vxe-column>
                  <vxe-column title="操作" :min-width="80">
                      <template #default="{ row }">
                          <el-button type="text" @click="selectHBClick(row)">选择</el-button>
                          <el-button type="text" @click="removeHBClick(row.code)">移除</el-button>
                      </template>
                  </vxe-column>
              </vxe-table>
          </div>
          <yunsuanfu :yinziList="state.yinziListHB" :biaodaList="state.biaodaList" :gasFuhao="true" @threeStep="threeStep" :expression="state.expression">
          </yunsuanfu>
          <div class="remarkBox">
              <p>组合累积计时重置时间</p>
              <el-time-picker
                v-model="state.formData.resetTime"
                placeholder="请选择"
                value-format="HH:mm:ss"
                format="HH:mm:ss"
              />
              <p>备注</p>
              <el-input :rows="3" v-model="state.formData.remark" type="textarea" placeholder="请输入">
              </el-input>
          </div>
          <div class="btnSubmit" style="margin:5px 0 0 15px;">
              <el-button type="info" @click="nextStep(9)">取消</el-button>
              <el-button type="info" @click="nextStep(1)">上一步</el-button>
              <el-button type="primary" @click="sumbitClick">保存</el-button>
          </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import list_controller from "@/components/commonCom/list_controller";
import { computed, onMounted, reactive } from "vue";
import { table_headers } from "@/components/commonCom/table_headers";
import axios from "@/utils/request";
import usePagesStore from "@/store/modules/pages";
import { ElMessage,ElMessageBox } from "element-plus";
  import {
    arrcompareRemove
  } from "@/utils/arrfun"
import stepcom from '../ybjConfig/zuheCom/stepcom.vue'
import yincard from '../ybjConfig/zuheCom/yincard.vue'
import yunsuanfu from '../ybjConfig/zuheCom/yunsuanfu.vue'
import _ from 'lodash'


const { proxy } = getCurrentInstance();
const store = usePagesStore();
const router = useRouter();
const upload = ref(null);
let state = reactive({
  options: {
    tableheads: computed(() => table_headers.configMergenceAccumulation),
    queryList: {
      dropdownUrl: "",
      querys: [],
      queryMap: new Map([]),
    },
    dataUrl: "/merge/accumulation/list",
  },
  querystwo: [{
      field: 'pointIds',
      title: '测点编号',
      type: 'input',
      binddata: ''
  }, {
      field: 'placeName',
      title: '安装地点',
      type: 'input',
      binddata: ''
  }],
  listAnalog:[],
  yinziList:[],
  yinziListHB:[],
  addModal:false,
  open_detail:false,
  formData:{},
  modalTitle:'',
  expression:'',
  biaodaList:[{
                name: '与',
                sub: '&&'
            }, {
                name: '或',
                sub: '||'
            },{
                name: '左括号',
                sub: '('
            },{
                name: '右括号',
                sub: ')'
            },{
                name: '撤',
                sub: '销'
            }, {
                name: '清',
                sub: '空'
            }]
});
const stepNum = ref(1)
const stepList = ref([
  {
    name: '设置名称',
    code: 1
  },
  {
    name: '选择因子',
    code: 2
  },
  {
    name: '分析条件',
    code: 3
  }
])
const yinziList = ref([])
const types = ref({})

// 获取列表
const getPipeList = () =>{
  axios.post('/combination/listSwitch',{}).then(res => {
    // state.listAnalog = res.data
    state.listAnalog= arrcompareRemove(res.data,state.yinziList,'pointId')
    state.listAnalog.forEach(item => {
      item.timeMod = []
      item.timeMod.push(...[item.highShow + '累积计时',item.lowShow + '累积计时'])
    })


  })
}
// 获取数据详情
const getDataInfo = (obj) =>{
  axios.post('/merge/accumulation/getById',{id:obj.id}).then(res => {
    state.formData = res.data
    state.formData.resetTime = res.data.accumulationTimeMode
    state.expression = state.formData.expression
    state.yinziList = []
    state.yinziListHB = []
    state.formData.pointDtoList.forEach(item => {
      if(item.marker){
        state.yinziList.push(item)
      }else{
        state.yinziListHB.push(item)
      }
    })
    state.yinziList.forEach(item => {
      item.pointId=item.code
      if(item.integration){
        item.title = item.code
      }else{
        item.title=item.name
        
      }
      item.objarr=[
          {left:'编号',right:item.code},
          {left:'名称',right:item.title},
          {left:'位置',right:item.place}
      ]
    })
    // state.yinziListHB.forEach(item => {
    //   item.code=item.name
    // })
  })
}
// 获取累积计时类型
const getTimeMods = () => {
  axios.get('/merge/accumulation/getTypes').then(res => {
    types.value = res.data
  })
}


// 打开新增弹窗
const addBtn = () => {
  state.addModal = true
  state.modalTitle = '新增'
  getPipeList()
  getTimeMods()
}
// 下一步
const nextStep = (n) => {
  if(n == 9){
    close()
  }
  if(n == 0){
    stepNum.value = 1
  }
  if(n == 1){
    if(state.formData.name && state.formData.name != ''){
      stepNum.value = 2
    }else{
      ElMessage.error('组合累积计时名称不能为空')
    }
  }else if(n == 2){
    console.log(state.yinziList,"state.yinziListstate.yinziList")
    if(state.yinziList.length==0){
      ElMessage.error('请先选择测点因子')
      stepNum.value = 2
    }else{
      stepNum.value = 3
      state.yinziList.forEach(item => {
        if(item.status == 'A' || item.integration){
          item.integration = true
          item.timeMod = ['正确累积计时','错误累积计时']
        }else{
          item.integration = false
          let arr = item.name.split('/')
          _.forIn(types.value, function(value, key) {
            if(key.includes(arr[0])){
              console.log(value);
              item.timeMod = value
            }
          });
        }
      })
    }
  }
}
// 选择行数据 
const selectClick = (row,index) => {
  row.marker = true
  row.title=row.sensorName
  row.code=row.pointId
  row.name=row.sensorName
  row.place=row.placeName
  row.objarr=[
      {left:'编号',right:row.code},
      {left:'名称',right:row.title},
      {left:'位置',right:row.placeName}
  ]
  if(state.yinziList.length == 0){
    state.yinziList.push(row)
  }else{
    let bl = state.yinziList.every(item => {
      return item.pointId != row.pointId
    })
    if(bl){
      state.yinziList.push(row)
    }
  }
  yinziList.value = state.yinziList
  state.listAnalog.splice(index,1)
}
// 第三步选择行数据
const selectHBClick = (row) => {
  if(row.accumulationTimeMode){
    state.yinziListHB.push(row)
    state.yinziListHB = JSON.parse(JSON.stringify(state.yinziListHB));
    state.yinziListHB.forEach(item => {
      item.marker = false
    })
  }else{
    ElMessage.warning('请选择累积计时模式')
  }
}
// 第三步移除数据
const removeHBClick = (code) => {
  let num
  state.yinziList.forEach((item,index) => {
    if(code == item.code){
      console.log(index);
      num = index
    }
  })
  state.yinziList.splice(num,1)
}
const threeStep = (list) => {
  state.formData.expression = list.expression
  state.formData.pointDtoList = []
  state.formData.pointDtoList.push(...state.yinziList)
  state.formData.pointDtoList.push(...state.yinziListHB)
}
// 关闭弹窗时执行
const close = () =>{
  state.addModal = false
  state.formData = {}
  stepNum.value = 1
  state.yinziList = []
  state.yinziListHB = []
  state.expression = ''
}
// 提交
const sumbitClick = () =>{
  if(!state.formData.resetTime){
    ElMessage.warning('请选择重置时间!')
  }else
  if(state.formData.expression){
    state.formData.status = "C"
    if(state.modalTitle.includes('新增')){
      axios.post('/merge/accumulation/add',state.formData).then(res => {
        if(res.code == 200){
          ElMessage.success(res.msg)
          close()
          proxy.$refs['zujianname'].getData()
        }
      })
    }else{
      axios.post('/merge/accumulation/modify',state.formData).then(res => {
        if(res.code == 200){
          ElMessage.success(res.msg)
          close()
          proxy.$refs['zujianname'].getData()
        }
      })
    } 
  }else{
    ElMessage.warning('请填入公式!')
  }
}
// 打开删除弹窗
const deleteBtn = (n,obj) =>{
  if(n == 0){
    let ids = []
    if (store.records.length > 0) {
      ids = store.records.map(item => {
        return item.id
      })
    } else {
      ElMessage.warning('请先勾选所要删除数据!');
    }
    if(ids.length > 0){
      ElMessageBox.confirm(
        '是否确认删除?',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(()=>{
        axios.post('/merge/accumulation/del',ids).then(res => {
          if (res.code == 200) {
            proxy.$refs['zujianname'].getData()
            proxy.$modal.msgSuccess(res.msg);
            store.records = []
          }
        })
      })
    }
  }else{
    ElMessageBox.confirm(
        '是否确认删除?',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(()=>{
        axios.post('/merge/accumulation/del',[obj.id]).then(res => {
          if (res.code == 200) {
            proxy.$refs['zujianname'].getData()
            proxy.$modal.msgSuccess(res.msg);
            store.records = []
            state.open_detail = false
          }
        })
      })
  }
} 
// 打开编辑弹窗
const editBtn = (row) => {
  state.addModal = true
  state.modalTitle = '修改'
  getPipeList()
  getTimeMods()
  getDataInfo(row)
}

onMounted(()=>{

})
</script>
<style lang="scss" scoped>
.addBox {
  padding: 42px 0;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.8);
  height: 99%;
  .step{
    height: calc(100% - 8px);
    overflow: auto;
  }
  .box_one{
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    .item{
      margin-bottom: 46px;
      display: flex;
      flex-direction: column;
    }
  }
  .p_title {
    font-size: 16px;
    font-weight: 700;
    padding: 0 10px;
  }
  .btnSubmit {
      margin-top: 40px;
      text-align: center;
  }
  .remarkBox {
      padding: 10px;
      font-size: 14px;
  }
}
</style>
